import React, { useState, useEffect } from 'react';
import Modal from '../../Modal';

interface ManualParseModalProps {
  isOpen: boolean;
  rawText: string;
  onContinue: (parsedData: any) => void;
  onCancel: () => void;
  showToast: (message: string, type?: 'success' | 'error') => void;
}

const ManualParseModal: React.FC<ManualParseModalProps> = ({ isOpen, rawText, onContinue, onCancel, showToast }) => {
  const [editableText, setEditableText] = useState(rawText);

  useEffect(() => {
    setEditableText(rawText);
  }, [rawText]);

  const handleContinue = () => {
    try {
      const parsed = JSON.parse(editableText);
      onContinue(parsed);
    } catch (e) {
      showToast("手动解析失败，请检查JSON格式。", "error");
    }
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onCancel}
      title="手动解析AI响应"
      footer={
        <div className="flex justify-end space-x-3">
          <button onClick={onCancel} className="px-4 py-2 bg-gray-600 hover:bg-gray-700 rounded text-white">取消</button>
          <button onClick={handleContinue} className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded text-white">重试解析并继续</button>
        </div>
      }
    >
      <div className="space-y-4">
        <p className="text-sm text-yellow-400">AI响应解析失败或已启用调试模式。请检查以下原始文本，修复任何JSON格式问题，然后重试。</p>
        <textarea
          value={editableText}
          onChange={(e) => setEditableText(e.target.value)}
          className="w-full h-64 bg-gray-900 text-gray-200 font-mono text-sm p-2 rounded border border-gray-600 focus:ring-2 focus:ring-blue-500 outline-none"
        />
      </div>
    </Modal>
  );
};

export default ManualParseModal;
